//logs.js
const chooseLocation = requirePlugin('chooseLocation');
var time = require("../../utils/util.js");
// 引用百度地图微信小程序JSAPI模块 
var bmap = require('../../libs/bmap-wx.min.js');
var wxMarkerData = []; //定位成功回调对象
const app = getApp()
import Dialog from '../../@vant/weapp/dialog/dialog';
import Toast from '../../@vant/weapp/toast/toast';
var rm = wx.getRecorderManager();
Page({
  data: {
    checked: '',
    id: '',
    ak: "KdZjo4KT7pfqWZovH40CIgtxOlFkax03", //填写申请到的ak
    fileList: [],
    value: '',
    time: '',
    type: '',
    text: '',
    address: '',
    typeid: '',
    tempFilePaths: '',
    images: [],
    videos: [],
    images1: [], //不加http
    videos1: [], //不加http
    videos2: [], //缩略图
    show: false,
    show1: false,
    lng: '',
    lat: '',
    activeNames: [],
    btnshow: false,
    bglist: [''], // 占位字符串不要删
    httpurl: time.httpurl,
    name: '语音',
    author: '',
    src: [],
    spare2: [],
    audio: true,
    showa: false,
    start: '',  
    accidentstatus: [],
    result: [],
  },
  recordStart: function(){
    this.setData({
      start: 'dot-blowup'
    })
    rm.start({
      format: 'mp3', 
    });
  },
  recordTerm: function(){
    var that = this;
    this.setData({
      start: '',
      showa: false
    })
    //结束录音  
    rm.stop();
    rm.onStop(function(res){
      // 停止录音之后，把录取到的音频放在res.tempFilePath 
      wx.uploadFile({
        url: time.httpurl + '/file/common/upload',
        filePath: res.tempFilePath,
        name: 'file',
        header: {
          'AppType': '1',
          'Authorization': wx.getStorageSync("token"),
        },
        success(data) {
          console.log(data)
          if (JSON.parse(data.data).code == 200) {            
            that.setData({  
              audio: false,
            })
            const arr = JSON.parse(data.data)
            if((res.duration/1000).toFixed(0) < 10){
              arr.time = "0" + (res.duration/1000).toFixed(0);
            }else{
              arr.time = (res.duration/1000).toFixed(0);
            }            
            const arraydata = [JSON.parse(data.data).fileName]
            that.setData({
              src: that.data.src.concat(arr)
            });
            that.setData({
              spare2: that.data.spare2.concat(arraydata)
            });
            console.log(that.data.src)
          }else {
            wx.showToast({
              title: JSON.parse(data.data).msg,
              icon: 'none',
              duration: 3000
            })
          }
        }
      })
     });
  },
  showaudio: function(){
    var that = this;
    wx.getSetting({
      success(res) {
        console.log(res.authSetting,res.authSetting['scope.record'])
        if (!res.authSetting['scope.record']) {
          wx.showModal({
            title: '麦克风授权',
            confirmText: '去设置',
            showCancel: false,
            content: '请授权麦克风权限，谢谢！',
            success: function(res) {
              if (res.confirm) {
                wx.openSetting({
                  success: res => {
                    if (res.authSetting['scope.record']) {
                      that.setData({
                        showa: true
                      })
                    } 
                  }
                });
              }
            }
          })
        }else if (res.authSetting['scope.record']){
          that.setData({
            showa: true
          })
        }
      }
    })
  },
  deleteaudio: function(e){
    console.log(e,this.data.src,this.data.spare2)
    var that = this;
    const index = e.currentTarget.dataset.index;
    const url = e.currentTarget.dataset.url;
    const src = that.data.src;
    src.splice(index, 1);
    that.setData({
      src: src
    });
    const spare2 = that.data.spare2;
    spare2.splice(index, 1);
    that.setData({
      spare2: spare2
    });
  },
  onCloseaudio() {
    this.setData({ showa: false });
  },
  onLoad: function (options) {
    console.log(options);
    var that = this
    that.setData({
      id: options.id
    })
    wx.authorize({
      scope: 'scope.record',
      success () {

      }
    })
    // wx.request({ 
    //   url: time.httpurl + '/app/getTaskInfo/'+options.id,
    //   method: 'GET',
    //   success: function (res) {
    //     console.log(res);
    //     if (res.data.code == 200) {
    //       // for(var i=0;i<res.data.data.length;i)          
    //       that.setData({
    //         recordlist: res.data.data
    //       })
    //     } else {
    //       wx.showToast({
    //         title: res.data.msg,
    //         icon: 'none',
    //         duration: 2000
    //       })
    //     }
    //   }
    // })
    wx.request({ 
      url: time.httpurl + '/event/app/getTaskDetails/'+options.id,
      method: 'GET',
      header: {
        'AppType': '1',
        'Authorization': wx.getStorageSync("token"),
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          that.setData({
            type: res.data.data.details,
            text: res.data.data.taskContent,
            address: res.data.data.address,
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
    wx.request({ 
      url: time.httpurl + '/event/app/getExigencyEventCoupleActionAll/'+options.etype,
      method: 'GET',
      header: {
        'AppType': '1',
        'Authorization': wx.getStorageSync("token"),
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          that.setData({
            accidentstatus: res.data.data,
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onReady: function () {
    var that = this;
    
  },
  //提交
  save: function () {
    var that = this;
    var taskStatus = null;
    console.log(that.data.images1)
    if(that.data.checked){
      taskStatus = 1;
    }else{
      taskStatus == 0
    }
    // if ( that.data.value == '' || taskStatus == 0) {
    //   wx.showToast({
    //     title: '您还没有填写任何信息，请填写,谢谢！',
    //     icon: 'none',
    //     duration: 2000
    //   })
    // }else {
      wx.request({ //提交
        url: time.httpurl + '/event/app/submitRecord',
        method: 'POST',
        header: {
          'AppType': '1',
          'Authorization': wx.getStorageSync("token"),
        },
        data: {
          "taskId":that.data.id,
          "imageListOb":that.data.images1,
          "handleRemark":that.data.value,
          "taskStatus":taskStatus,
          "openid": wx.getStorageSync('openId'),
          "voice": that.data.spare2.join(',')
        },
        success: function (res) {
          // console.log(res,'提交');
          if (res.data.code == 200) {
            wx.navigateBack({
              url: '../index/index'
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    // }
  },
  saverequest: function () {
    var that = this;
    
  },
  //本地上传图片
  localupload: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        console.log(res);
        that.setData({
          show: false
        });
        wx.uploadFile({
          url: time.httpurl + '/file/common/upload',
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            'AppType': '1',
            'Authorization': wx.getStorageSync("token"),
          },
          success(data) {
            console.log(data)
            if (JSON.parse(data.data).code == 200) {
              const arraydata = [JSON.parse(data.data).fileName]
              that.setData({
                images: that.data.images.concat([time.httpurlvideo + JSON.parse(data.data).fileName])
              });
              that.setData({
                images1: that.data.images1.concat(arraydata)
              });
            }else {
              wx.showToast({
                title: JSON.parse(data.data).msg,
                icon: 'none',
                duration: 3000
              })
            }
          }
        })
      }
    })
  },
  //拍照
  camera: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: function (res) {
        // console.log(res)
        that.setData({
          show: false
        });
        wx.uploadFile({
          url: time.httpurl + '/file/common/upload',
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            'AppType': '1',
            'Authorization': wx.getStorageSync("token"),
          },
          success(data) {
            // console.log(data)
            if (JSON.parse(data.data).code == 200) {
              const arraydata = [JSON.parse(data.data).fileName]
              that.setData({
                images: that.data.images.concat([time.httpurlvideo + JSON.parse(data.data).fileName])
              });
              that.setData({
                images1: that.data.images1.concat(arraydata)
              });
            }else {
              wx.showToast({
                title: JSON.parse(data.data).msg,
                icon: 'none',
                duration: 3000
              })
            }
          }
        })
      }
    })
  },
  //本地上传视频
  uploadvideo: function () {
    var that = this;
    wx.chooseVideo({
      maxDuration: 15,
      sourceType: ['album'],
      success: function (res) {
        // console.log(res); 
        that.setData({
          show: false
        });
        if (res.duration > 15) {
          Dialog.confirm({
            message: '上传视频时长不能超过15秒，请剪辑后上传',
          })
        } else {
          Toast.loading({
            message: '上传中...',
            forbidClick: true,
          });
          that.upvideo(res.tempFilePath);
        }

      }
    })
  },
  upvideo: function (filePath) {
    var that = this;
    wx.uploadFile({
      url: time.httpurl + '/file/common/upload',
      filePath: filePath,
      name: 'file',
      timeout: 180000,
      header: {
        'AppType': '1',
        'Authorization': wx.getStorageSync("token"),
      },
      success(data) {
        // console.log(data) 
        Toast.clear();
        if (JSON.parse(data.data).code == 200) {
          const arr = [time.httpurlvideo + JSON.parse(data.data).data.webPath]
          that.setData({
            videos: that.data.videos.concat(arr)
          });
          that.setData({
            videos1: that.data.videos1.concat([JSON.parse(data.data).data.webPath])
          });
          that.setData({
            videos2: that.data.videos2.concat([JSON.parse(data.data).data.videoImageWebPath])
          });
          if (that.data.images.length + that.data.videos.length == 3) {
            that.setData({
              show1: true
            });
          }
        } else if (JSON.parse(data.data).code == 401 || JSON.parse(data.data).code == 403) {
          app.login();
        } else {
          wx.showToast({
            title: JSON.parse(data.data).msg,
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
  },
  //拍摄
  shot: function () {
    var that = this
    wx.chooseVideo({
      maxDuration: 15,
      sourceType: ['camera'],
      success: function (res) {
        // console.log(res)  
        that.setData({
          show: false
        });
        Toast.loading({
          message: '上传中...',
          forbidClick: true,
        });
        wx.uploadFile({
          url: time.httpurl + '/file/common/upload',
          filePath: res.tempFilePath,
          name: 'file',
          timeout: 180000,
          header: {
            'AppType': '1',
            'Authorization': wx.getStorageSync("token"),
          },
          success(data) {
            // console.log(time.httpurlvideo,JSON.parse(data.data)) 
            Toast.clear();
            if (JSON.parse(data.data).code == 200) {
              const arr = [time.httpurlvideo + JSON.parse(data.data).data.webPath]
              that.setData({
                //上传完并显示照片
                videos: that.data.videos.concat(arr)
              });
              that.setData({
                videos1: that.data.videos1.concat([JSON.parse(data.data).data.webPath])
              });
              that.setData({
                videos2: that.data.videos2.concat([JSON.parse(data.data).data.videoImageWebPath])
              });
              if (that.data.images.length + that.data.videos.length == 3) {
                that.setData({
                  show1: true
                });
              }
            } else if (JSON.parse(data.data).code == 401 || JSON.parse(data.data).code == 403) {
              app.login();
            } else {
              wx.showToast({
                title: JSON.parse(data.data).msg,
                icon: 'none',
                duration: 3000
              })
            }
          }
        })
      }
    })
  },
  // 删除照片
  delete: function (e) {
    // console.log(e);
    var that = this;
    const index = e.currentTarget.dataset.index;
    const url = e.currentTarget.dataset.url;
    if (url.charAt(url.length - 1) == 'g') {
      const images = that.data.images;
      images.splice(index, 1);
      that.setData({
        images: images
      });
      const images1 = that.data.images1;
      images1.splice(index, 1);
      that.setData({
        images1: images1
      });
    } else {
      const videos = that.data.videos;
      videos.splice(index, 1);
      that.setData({
        videos: videos
      });
      const videos1 = that.data.videos1;
      videos1.splice(index, 1);
      that.setData({
        videos1: videos1
      });
      const videos2 = that.data.videos2;
      videos2.splice(index, 1);
      that.setData({
        videos2: videos2
      });
    }
    // console.log(that.data.images,that.data.images1,that.data.videos,that.data.videos1)
    if (this.data.images.length + this.data.videos.length == 2) {
      this.setData({
        show1: false
      });
    }
  }, 
  showPopup() {
    this.setData({
      show: true
    });
  },
  onChangestatus(event) {
    console.log(event)
    this.setData({
      result: event.detail,
    });
    this.setData({
      value: event.detail.join(',')
    })
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: detail });
  },
  onChangecollapse(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  record(){
    wx.navigateTo({
      url: '../record/record?id=' + this.data.id,
    })
  },
  //地图选点
  location() {
  
  },
  //地图选点返回结果
  onShow() {
   
  },
  /**
   * 坐标系转化
   */
  gcj02tobd09: function (lng, lat) {
    var that = this
    var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    var PI = 3.1415926535897932384626;
    var a = 6378245.0;
    var ee = 0.00669342162296594323;
    var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
    var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
    var bd_lng = z * Math.cos(theta) + 0.0065;
    var bd_lat = z * Math.sin(theta) + 0.006;
    return [bd_lng, bd_lat]
  },
})